package com.teangtang.fly.service;

import com.teangtang.fly.dto.FindFlightDTO;
import com.teangtang.fly.dto.FlightDto;
import com.teangtang.fly.entity.Airline;
import com.teangtang.fly.entity.Flight;
import com.teangtang.fly.repository.AirlineRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

@Service
public class AirlineService {

    @Autowired
    private AirlineRepository airlineRepository;

    @Autowired
    private FlightService flightService;

    public List<Airline> getAllAirlines() {
        return airlineRepository.findAll();
    }

    public Airline getAirlineByAirlineNumber(String flightNumber) {
        return airlineRepository.findById(flightNumber).orElse(null);
    }

    public List<FlightDto> getFlightByCityAndTime(FindFlightDTO findFlightDTO){
        String startDateString = findFlightDTO.getStartDate().toString();
        LocalDate startDate = LocalDate.parse(startDateString, DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH));
        List<Airline> airlines = airlineRepository.findAll();
        List<Flight> findFlight = new ArrayList<>();
        for(Airline airline : airlines){
            if(airline.getDepartureCity().getCityCode()==findFlightDTO.getDepartureCityCode()&&airline.getArrivalCity().getCityCode()==findFlightDTO.getArrivalCityCode()){
                List<Flight> flights = airline.getFlights();
                for(Flight flight : flights){
                    LocalDate flightStartDate = LocalDate.parse(flight.getStartDate().toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    if(startDate.isEqual(flightStartDate)){
                        findFlight.add(flight);
                    }
                }
            }
        }

        return flightService.turnFlightsToFlightDto(findFlight,0);
    }

    public Airline createAirline(Airline airline) {
        return airlineRepository.save(airline);
    }

    public Airline updateAirline(String airlineNumber, Airline airline) {
        airline.setAirlineNumber(airlineNumber);
        return airlineRepository.save(airline);
    }

    public void deleteAirline(String airlineNumber) {
        airlineRepository.deleteById(airlineNumber);
    }
}
